package com.qsmx.qingqiuticket.app.delegate.back;

import android.Manifest;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.PermissionChecker;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateVersionListBinding;
import com.qsmx.qingqiuticket.app.delegate.back.adapter.VersionAdapter;
import com.qsmx.qingqiuticket.app.entity.VersionEntity;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.DownloadUtil;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.lang.reflect.Type;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class BackCheckVersionDelegate extends AtmosDelegate {

    private DelegateVersionListBinding mBinding;
    private VersionAdapter mAdapter;
    private VersionEntity mData;

    @Override
    public Object setLayout() {
        return R.layout.delegate_version_list;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mBinding = DelegateVersionListBinding.bind(rootView);
        initRecycler();
        initRefresh();

        mBinding.tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSupportDelegate().pop();
            }
        });
    }

    private void initRefresh() {
        mBinding.refreshLayout.autoRefresh();
        mBinding.refreshLayout.setEnableLoadMore(false);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initVersionData();
            }
        });

    }

    private void initVersionData() {
        JSONObject params = new JSONObject();

        HttpHelper.RestClientPostRaw(params, HttpUrl.CUR_MACHINE_PACKAGE,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        mBinding.refreshLayout.finishRefresh();
                        try {
                            Type type = new TypeToken<VersionEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            mData = gson.fromJson(response, type);

                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                if (mData.getBody() != null && mData.getBody().size() > 0) {
                                    mAdapter.setData(mData.getBody());
                                    mAdapter.notifyDataSetChanged();
                                    mBinding.tvHasNoInfo.setVisibility(View.GONE);
                                    mBinding.rlvUpdateList.setVisibility(View.VISIBLE);
                                } else {
                                    mBinding.rlvUpdateList.setVisibility(View.GONE);
                                    mBinding.tvHasNoInfo.setVisibility(View.VISIBLE);
                                }
                            } else {
                                DialogUtil.showCardErrorDialog(BackCheckVersionDelegate.this, getContext(), "更新信息拉取失败", "确定");
                            }

                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(BackCheckVersionDelegate.this, getContext(), response, "确定");
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.showCardErrorDialog(BackCheckVersionDelegate.this, getContext(), msg, "确定");
                        mBinding.refreshLayout.finishRefresh();
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.showCardErrorDialog(BackCheckVersionDelegate.this, getContext(), getString(R.string.un_know_error), "确定");
                        mBinding.refreshLayout.finishRefresh();
                    }
                });
    }

    private void initRecycler() {

        mAdapter = new VersionAdapter(getContext());
        LinearLayoutManager manager = new LinearLayoutManager(getContext());

        mBinding.rlvUpdateList.setAdapter(mAdapter);
        mBinding.rlvUpdateList.setLayoutManager(manager);

        mAdapter.setonItemClickListener(new VersionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                downloadFile(mData.getBody().get(position).getDownloadUrl(), mData.getBody().get(position).getVersion());
            }
        });

    }

    private void downloadFile(String downLoadUrl, String version) {
        BackCheckVersionDelegatePermissionsDispatcher.startCheckUpdateWithCheck(BackCheckVersionDelegate.this, downLoadUrl, version);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startCheckUpdate(String url, String version) {
        DownloadUtil.DownLoadFile(requireContext(), url, version + "-" + System.currentTimeMillis(), "青丘自助售票机", url.split("\\.")[url.split("\\.").length - 1]);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileRational(PermissionRequest request) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BackCheckVersionDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
